//
//  ViewController.m
//  XMMusicTest
//
//  Created by sfk-ios on 2017/7/10.
//  Copyright © 2017年 sfk-JasonSu. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
// 锁屏显示
#import <MediaPlayer/MediaPlayer.h>

#import "ViewController.h"
#import "SFKHTTPTool.h"
#import "XMMuiscConstant.h"
#import "MBProgressHUD+MJ.h"
#import "MJExtension.h"
#import "XMSearchMusicModel.h"
#import "UIImageView+WebCache.h"
#import "FLAnimatedImageView+WebCache.h"
#import "FLAnimatedImage.h"

#import "SettingViewController.h"
#import "AlbumListController.h"

typedef enum : NSUInteger { // -- 循环模式
    PlayLoopModeSingle = 1,  // 单曲循环
    PlayLoopModeAll,  // 列表循环
    PlayLoopModeFree,  // 随机播放
} PlayLoopMode;

#define albumImageViewAnimationKey @"rotationAnimation"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *bgImgView;
@property (weak, nonatomic) IBOutlet UIView *playAreaBgView;
@property (weak, nonatomic) IBOutlet UITextField *searchF;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *nowPlayL;
/// 播放器
@property (strong, nonatomic) AVPlayer *player;
/// 当前播放时间监听
@property (nonatomic ,strong)  id timeObser;
/// 播放进度条
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
/// 当前缓冲了的进度条
@property (weak, nonatomic) IBOutlet UIProgressView *canPlayProgressView;
@property (weak, nonatomic) IBOutlet UILabel *playTimeL;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeL;
@property (weak, nonatomic) IBOutlet UILabel *networkL;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *lastSongBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextSongBtn;
@property (weak, nonatomic) IBOutlet UIButton *settingBtn;
@property (weak, nonatomic) IBOutlet UIButton *mySongListBtn;
@property (weak, nonatomic) IBOutlet UIButton *likeAddBtn;
@property (weak, nonatomic) IBOutlet UIButton *loopModeBtn;
@property (weak, nonatomic) IBOutlet UIButton *fullScreenBtn;
/// 播放器音量
@property (strong, nonatomic) MPVolumeView *volumeView;
/// 音量条
@property (strong, nonatomic) UISlider *volumeSlider;
@property (strong, nonatomic) UISlider *showVolueSlider;
/// 全屏播放时玻璃效果toolbar
@property (strong, nonatomic) UIToolbar *bgToolBar;
/// 全屏播放时的封面图册
@property (weak, nonatomic) UIImageView *albumImgView;
/// 全屏播放时的歌曲名
@property (weak, nonatomic) UILabel *fullScreenSongNameL;
/// 全屏播放时的歌手
@property (weak, nonatomic) UILabel *fullScreenSingerNameL;
/// 正在播放歌曲指示圆点
//@property (weak, nonatomic) UIView *playingView;
/// 自转动画
@property (strong, nonatomic) CABasicAnimation* rotationAnimation;

/// 当前播放的序号
@property (assign, nonatomic) NSInteger currentPlayIndex;
/// 播放总时长
@property (nonatomic,assign) CGFloat sumPlayOperation;
/// 搜索到的歌曲数据
@property (strong, nonatomic) NSMutableArray *searchData;
/// 当前播放时间
@property (assign, nonatomic) int playTime;
/// 循环模式
@property (assign, nonatomic) PlayLoopMode playMode;
/// 当前播放的歌曲
@property (strong, nonatomic) XMSearchMusicModel *currentPlaySong;
/// 是否刷新了歌曲列表
@property (assign, nonatomic) BOOL hadRefreshData;
@property (assign, nonatomic) BOOL isPlaying;
/// 播放下一曲
@property (assign, nonatomic) BOOL startPlaying;
/// 是否打开全屏播放
@property (assign, nonatomic) BOOL isShowBgToolBar;

@end

@implementation ViewController

- (NSMutableArray *)searchData
{
    if (!_searchData) {
        _searchData = [NSMutableArray array];
    }
    return _searchData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
/**
 * 注意：iOS 10以上真机调试不能在控制台打印，原因是在项目中 edit scheme 中的 argument 中设置了 OS_ACTIVITY_MODE -> disable , 可以去掉该变量，或者用模拟器调试打印（主要是打印网络测试数据）。
     其他效果测试，建议用真机。
 */
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
    
    _searchF.returnKeyType = UIReturnKeyDone;
    _searchF.delegate = self;
    _searchBtn.layer.cornerRadius = 5;
    _searchBtn.clipsToBounds = YES;
    
    // continuous属性设成NO,会在手指离开的时候触发一次valueChange事件，而不是在拖动的过程中不断触发valueChange事件
    _progressSlider.continuous = NO;
    
    // 让背景图放在最底层
    [self.view sendSubviewToBack:_playAreaBgView];
    [self.view sendSubviewToBack:_bgImgView];
    
    //设置播放进度的默认值
    self.progressSlider.value = 0;
    // 未播放状态
    _playBtn.selected = NO;
    self.isPlaying = NO;
    // 当前播放歌曲序列
    _currentPlayIndex = 0;
    _hadRefreshData = NO;
    
    // 加载默认的“周杰伦”歌曲数据
//    [self loadDefualtData];
    
    // 设置自定义设置
    [self setUserDefaults];
    
    // 初始化各类通知
    [self setUpNotifications];
    
}


/// 初始化各类通知
- (void)setUpNotifications
{
    // 监听程序进入前台运行
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAppDidBecomeActive) name:NOTI_BECOME_ACTIVE object:nil];
    
    // 监听歌曲播放完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    // 监听系统声音变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:NOTI_SYSTEM_VOLUM_CHANGE object:nil];
    
    // 设置背景图片
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setBgImage:) name:NOTI_SET_BGIMAGE object:nil];
    
    // 设置背景图片透明度
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setBgImageAlpha:) name:NOTI_SET_BGIMAGE_ALPHA object:nil];
    
    // 设置TableView背景透明度 SetTableViewBgAlpha
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTableViewBgAlpha:) name:NOTI_SET_TABLEBG_ALPHA object:nil];
    
    // 重新设置播放列表的数据为 “我的收藏”中的歌曲
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMyAlbumSongs:) name:NOTI_PLAY_ALBUM object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // 开始接受远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
//    if (self.isPlaying) {
//        [self makeImgViewCircleAnimationWithState:1];
//    }
    NSLog(@"viewWillAppear");
}

- (void)viewWillDisappear:(BOOL)animated {
    // 接触远程控制
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (void)dealloc
{
    [self.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    [self removePlayerTimerObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 自定义设置配置
/// 设置自定义设置
- (void)setUserDefaults
{
    // 设置自定义背景图
    [self setBgImageViewImage];
    
//    NSLog(@"bgImageAlpha---%@",[UserDefaultsTool userDefaults].bgImageAlpha);
//    NSLog(@"playListBgAlpha===%@",[UserDefaultsTool userDefaults].playListBgAlpha);
    
    // 设置自定义背景图的透明度
    NSNumber *imageNum = [UserDefaultsTool userDefaults].bgImageAlpha?:@50;
    self.bgImgView.alpha = [imageNum integerValue]/100.0;
    // 设置播放列表自己的背景透明度
    NSNumber *listNum = [UserDefaultsTool userDefaults].playListBgAlpha?:@80;
    self.tableView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:[listNum integerValue]/100.0];
    NSLog(@"[UserDefaultsTool userDefaults].playLoopMode==%@",[UserDefaultsTool userDefaults].playLoopMode);
    // 播放模式
    self.playMode = [UserDefaultsTool userDefaults].playLoopMode?[[UserDefaultsTool userDefaults].playLoopMode integerValue]:PlayLoopModeAll;
    NSLog(@"self.playMode==%ld",self.playMode);
    if (self.playMode != PlayLoopModeAll) {
        NSString *imgName = (self.playMode == PlayLoopModeFree) ? @"随机播放" : @"单曲循环";
        [self.loopModeBtn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    }
    
    // 判断是否默认显示“我的收藏歌单”
    if ([[UserDefaultsTool userDefaults].playListDefaultMyAlbum isEqualToString:@"1"]) {
        
        // 歌单中的歌曲数据
        NSArray *array = [XMSearchMusicModel bg_find:DEFAULT_TABLE_NAME where:nil];
        self.searchData = [NSMutableArray arrayWithArray:array];
        
        if (!self.searchData.count) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD showSingleMessage:@"我的收藏中还没有歌曲~"];
            });
        }
    }else {
        
        [self loadDefualtData];
    }
    
}

/// 当程序重新打开时
- (void)handleAppDidBecomeActive
{
    // 检查网络状态
    [self checkNetworkState];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if (self.isPlaying) {
//            NSLog(@"handleAppDidBecomeActive == self.isPlaying");
//            [self makeImgViewCircleAnimationWithState:YES];
//        }
//    });
}

// 重写父类成为响应者方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

#pragma mark - 网络数据处理<begin>
/// 第一次打开界面加载“周杰伦”数据
- (void)loadDefualtData
{
    [MBProgressHUD showMessage:@"" toView:self.view];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",API_ROOT,SEARCH_SONG];
    NSMutableDictionary *pramas = [NSMutableDictionary dictionary];
    pramas[@"key"] = @"周杰伦";
    pramas[@"page"] = @"1";
    pramas[@"limit"] = @"20";  // iPhone7刚好显示9条
    
//    [MBProgressHUD showMessage:@"" toView:self.view];
    
    [SFKHTTPTool GET:urlString parameters:pramas success:^(NSURLSessionTask *task, id JSON) {
        
        NSLog(@"歌曲返回==%@",JSON);
        [MBProgressHUD hideHUDForView:self.view];
        
        self.searchData = [XMSearchMusicModel mj_objectArrayWithKeyValuesArray:JSON[@"songList"]];
        _currentPlayIndex = 0;
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"请求失败"];
        NSLog(@"搜索歌曲失败==%@",error);
    }];
    
    /// 查看当前网络连接状态
    [self checkNetworkState];
}

/// 点击搜索音乐
- (IBAction)searchMusic:(id)sender {
    
    if (!self.searchF.text.length) {
        [MBProgressHUD showError:@"请输入搜索关键字"];
        return;
    }
    
    [self.view endEditing:YES];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",API_ROOT,SEARCH_SONG];
    NSMutableDictionary *pramas = [NSMutableDictionary dictionary];
    pramas[@"key"] = _searchF.text;
    pramas[@"page"] = @"1";
    pramas[@"limit"] = @"20";  // iPhone7刚好显示9条
    
    [MBProgressHUD showMessage:@"" toView:self.view];
    
    [SFKHTTPTool GET:urlString parameters:pramas success:^(NSURLSessionTask *task, id JSON) {
        
        NSLog(@"搜索歌曲返回==%@",JSON);
        [MBProgressHUD hideHUDForView:self.view];
        
        if (self.searchData.count>0) {
            _hadRefreshData = YES;
        }
        
        self.searchData = [XMSearchMusicModel mj_objectArrayWithKeyValuesArray:JSON[@"songList"]];
        _currentPlayIndex = 0;
        self.isPlaying = NO;
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"请求失败"];
        NSLog(@"搜索歌曲失败==%@",error);
    }];
    
    /// 查看当前网络连接状态
    [self checkNetworkState];
}

/// 获取歌曲播放路径
- (void)getSongInfoWithSong:(XMSearchMusicModel *)song
{
    // 发送网络请求获取歌曲播放路径
    NSString *urlString = [NSString stringWithFormat:@"%@%@",API_ROOT,GET_SONG];
    NSMutableDictionary *pramas = [NSMutableDictionary dictionary];
    pramas[@"id"] = song.ID;
    
    [SFKHTTPTool GET:urlString parameters:pramas success:^(NSURLSessionTask *task, id JSON) {
        
        NSLog(@"获取歌曲返回==%@",JSON);
        [MBProgressHUD hideHUDForView:self.view];
        if ([JSON[@"success"] integerValue] == 1) {
            
            NSString *urlStr = JSON[@"url"];
            [self startPlayWithURL:urlStr];
        
            // 设置锁屏状态播放信息
            [self setupNotificationSong:song];
            self.currentPlaySong = song;
            
//            XMSearchMusicModel *song = self.searchData[_currentPlayIndex];
            NSString *imgStr = song.album[@"cover"];
            [_albumImgView sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"winterCute.png"]];
            _fullScreenSongNameL.text = song.name;
            NSDictionary *artists = song.artists.firstObject;
            NSString *singerName = artists[@"name"];
            _fullScreenSingerNameL.text = singerName;
            
        }else {
            [MBProgressHUD showError:@"播放请求出错"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self nextSong:_nextSongBtn];
            });
        }
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"请求失败"];
        [self playBtnClick:_playBtn];
        NSLog(@"获取歌曲失败==%@",error);
    }];
    
    /// 查看当前网络连接状态
    [self checkNetworkState];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *searchCellID = @"searchCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchCellID];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:searchCellID];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.detailTextLabel.textColor = [UIColor grayColor];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        
//        UIView *playingL = [[UIView alloc]initWithFrame:CGRectMake(cell.frame.size.width -20, 20, 10, 10)];
//        playingL.backgroundColor = [UIColor orangeColor];
//        playingL.layer.cornerRadius = 5;
//        playingL.clipsToBounds = YES;
//        [cell addSubview:playingL];
//        cell.accessoryView = playingL;
        
        FLAnimatedImageView *imgView = [FLAnimatedImageView new];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.frame = CGRectMake(-20, 20, 13, 13);
        NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]]pathForResource:@"playing" ofType:@"gif"];
        NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
        imgView.backgroundColor = [UIColor clearColor];
        imgView.animatedImage = [FLAnimatedImage animatedImageWithGIFData:imageData];
//        [cell addSubview:imgView];
        cell.accessoryView = imgView;
    }
    
    XMSearchMusicModel *song = _searchData[indexPath.row];
    
    // 缩略图
    NSString *imgStr = song.album[@"coverSmall"];
    NSString *albumName = song.album[@"name"];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imgStr?:@""] placeholderImage:[UIImage imageNamed:@"nomssg_icon"]];
    // 歌曲名
    cell.textLabel.text = song.name;
    // 歌手
    NSDictionary *artists = song.artists.firstObject;
    NSString *singerName = artists[@"name"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",singerName,albumName];
    
    if (indexPath.row == _currentPlayIndex) {
        cell.textLabel.textColor = [UIColor orangeColor];
        if (self.isPlaying && [song isEqual:_currentPlaySong]) {
            cell.accessoryView.hidden = NO;
        }else{
            cell.accessoryView.hidden = YES;
        }
    }else {
        cell.accessoryView.hidden = YES;
        cell.textLabel.textColor = [UIColor blackColor];
    }
    
    return cell;
}

#pragma mark  UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _hadRefreshData = NO;
    
    XMSearchMusicModel *song = _searchData[indexPath.row];
    [self getSongInfoWithSong:song];
    _currentPlayIndex = indexPath.row;
    _playTime = 0;
    [_player pause];
    
    self.isPlaying = NO;
    [self.tableView reloadData];
}

#pragma mark - AVPlayer 相关
//////// 以下是播放 相关
- (void)startPlayWithURL:(NSString *)URL
{
    [self.player pause];
    [self removePlayerTimerObserver];
    
    NSURL *url = [NSURL URLWithString:URL];
    
    //设置播放的项目
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
    //初始化player对象
    if (self.player.currentItem) {
        [[self.player currentItem] removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
        [[self.player currentItem] removeObserver:self forKeyPath:@"status" context:nil];
        [self.player replaceCurrentItemWithPlayerItem:item];
    }else {
        self.player = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    // 监听播放状态
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    // 监听loadedTimeRanges属性
    [item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    // 监听时间
    [self addPlayerTimerObserver];
    
//    //设置播放页面(视频)
//    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
//    //设置播放页面的大小
//    layer.frame = CGRectZero;
//    layer.backgroundColor = [UIColor cyanColor].CGColor;
//    //设置播放窗口和当前视图之间的比例显示内容
//    layer.videoGravity = AVLayerVideoGravityResizeAspect;
//    //添加播放视图到self.view
//    [self.view.layer addSublayer:layer];
    
    //设置播放进度的默认值
    self.progressSlider.value = 0;
    //设置播放的默认音量值
    self.player.volume = 1.0f;
    
    _playBtn.selected = YES;
    _nowPlayL.text = @"缓冲中...";
     [self.canPlayProgressView setProgress:0.0 animated:NO];
}

- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString*, id> *)change context:(nullable void *)context {
    
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = self.player.currentItem.status;
        switch (status) {
            case AVPlayerItemStatusReadyToPlay:
            {
                NSLog(@"AVPlayerItemStatusReadyToPlay");
                // 开始播放
                if (self.isPlaying && self.currentPlaySong) {
                    
                }else {
                    _playTime = 0;
                }
                [self.player play];
//                [self startTimer];
                XMSearchMusicModel *song = self.currentPlaySong;
                _nowPlayL.text = [NSString stringWithFormat:@"正在播放: %@",song.name];
                [self setupNotificationSong:song];
                self.isPlaying = YES;
                self.startPlaying = YES;
                self.sumPlayOperation = self.player.currentItem.duration.value/self.player.currentItem.duration.timescale;
                NSInteger min = (NSInteger)self.sumPlayOperation/60;
                NSInteger second = (NSInteger)self.sumPlayOperation%60;
                _totalTimeL.text = [NSString stringWithFormat:@"%02ld:%02ld",min,second];
                // 让图册自转
                [self makeImgViewCircleAnimationWithState:1];
                // 开始封面自转动画
                [self resumeLayer:self.albumImgView.layer];
                [self.tableView reloadData];
            }
                break;
            case AVPlayerItemStatusUnknown:
            {
                NSLog(@"AVPlayerItemStatusUnknown");
                [MBProgressHUD showSingleMessage:@">_< 喔哦~~"];
                self.playBtn.selected = NO;
                [self.player pause];
            }
                break;
            case AVPlayerItemStatusFailed:
            {
                NSLog(@"AVPlayerItemStatusFailed");
                _playBtn.selected = NO;
                _nowPlayL.text = @"播放失败";
                [MBProgressHUD showError:@"播放失败"];
//                self.isPlaying = NO;
//                self.playBtn.selected = NO;
                //                [self.player pause];
                [[self.player currentItem] removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
                [[self.player currentItem] removeObserver:self forKeyPath:@"status" context:nil];
                self.player = nil;
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self nextSong:_nextSongBtn];
                });
//                [self stopTimer];
            }
                break;
                
            default:
                break;
        }
    }else if ([keyPath isEqualToString:@"loadedTimeRanges"]){
        
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        NSLog(@"Time Interval:%f",timeInterval);
        /// iOS 10以上不能通过这个边缓存边播放
        if ((timeInterval-self.playTime > 20) && self.playBtn.selected) {
            XMSearchMusicModel *song = self.currentPlaySong;
            _nowPlayL.text = [NSString stringWithFormat:@"正在播放: %@",song.name];
            [self.player play];
        }else if (timeInterval >= self.sumPlayOperation){  // 完全缓冲完毕
            
        }else {  // 正在缓冲
            
            XMSearchMusicModel *song = self.currentPlaySong;
            _nowPlayL.text = [NSString stringWithFormat:@"正在缓冲: %@",song.name];
        }
        CMTime duration = self.player.currentItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.canPlayProgressView setProgress:timeInterval / totalDuration animated:YES];
    }
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}


#pragma mark - TimerObserver 播放时间监听
- (void)addPlayerTimerObserver
{
    __weak typeof (self)self_ = self;
    _timeObser = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        // 滑动slider进度（0~1）
        float currentTimeValue = time.value*1.0/time.timescale/self_.sumPlayOperation;
        self_.progressSlider.value = currentTimeValue;
        
        // 播放时间
        self_.playTime = (int)(time.value/time.timescale);
        NSString *currentString = [self_ getStringFromCMTime:time];
        self_.playTimeL.text = currentString;
//        NSLog(@"self_.playTime==%d",self_.playTime);
//        NSLog(@"currentTimeValue==%f, currentString==%@",currentTimeValue,currentString);
        [self_ setupNotificationSong:self_.currentPlaySong];
        self_.isPlaying = YES;
    }];
}

- (void)removePlayerTimerObserver {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    [_player removeTimeObserver:_timeObser];
}


- (NSString *)getStringFromCMTime:(CMTime)time
{
    float currentTimeValue = (CGFloat)time.value/time.timescale;//得到当前的播放时
    
//    NSLog(@"currentTimeValue==%f",currentTimeValue);
    NSDate * currentDate = [NSDate dateWithTimeIntervalSince1970:currentTimeValue];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
    NSDateComponents *components = [calendar components:unitFlags fromDate:currentDate];
    
    if (currentTimeValue >= 3600 )
    {
        return [NSString stringWithFormat:@"%ld:%02ld:%02ld",components.hour,components.minute,components.second];
    }
    else
    {
        return [NSString stringWithFormat:@"%02ld:%02ld",components.minute,components.second];
    }
}

/// 播放结束
- (void)playToEnd:(NSNotification *)notic {
    
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    if (self.playMode == PlayLoopModeSingle) {  // 单曲循环
        _playTime = 0;
        _playTimeL.text = [NSString stringWithFormat:@"00:00"];
        [self.player seekToTime:CMTimeMakeWithSeconds(0, self.player.currentItem.duration.timescale) completionHandler:^(BOOL finished) {
            [self.player play];
            //                [self startTimer];
        }];
        
    }else {   // 不是单曲循环
        
        if (self.startPlaying == YES) {  // 如果已经开始播放
            self.startPlaying = NO;
            [self nextSong:nil];
        }
    }
}


#pragma mark - 界面交互操作
/// 滑动改变歌曲播放进度
- (IBAction)changeProgress:(id)sender {
    
    if (_nowPlayL.text.length==0) {
        
        return;
    }
    
    self.sumPlayOperation = self.player.currentItem.duration.value/self.player.currentItem.duration.timescale;
    
    CGFloat value = _progressSlider.value;
    _playTime = (int)(value *self.sumPlayOperation);
    
    NSLog(@"progressDidChange _playTime==%d",_playTime);
    
//    NSLog(@"value == %f",value);
    //CMTimeMake(a,b) a表示当前时间，b表示每秒钟有多少帧
    [self.player seekToTime:CMTimeMakeWithSeconds(_playTime, self.player.currentItem.duration.timescale) completionHandler:^(BOOL finished) {
        [self.player play];
    }];
}


/// 点击了暂停/播放按钮
- (IBAction)playBtnClick:(UIButton *)sender {
    
    if (!self.searchData.count) {
        return;
    }
    
    
    if (sender.selected) {  // 点击时播放中
        
        self.isPlaying = NO;
        [self.player pause];
        
        /// 暂停封面图册自转动画
        [self pauseLayer:self.albumImgView.layer];
        
    }else {  // 点击时暂停状态
        
        
        if ((_rotationAnimation.duration < 10) && self.albumImgView) {
            // 开始封面自转动画
            [self makeImgViewCircleAnimationWithState:1];
            NSLog(@" **** 开始封面自转动画");
        }else{
            
            NSLog(@" **** 继续 ===%@",self.albumImgView);
            // 继续
            [self resumeLayer:self.albumImgView.layer];
        }
        
        if (self.sumPlayOperation > 0) {
            
            self.isPlaying = YES;
            [self.player play];
            
        }else {
            if (self.searchData.count >0) {
                XMSearchMusicModel *firstSong = self.searchData.firstObject;
                [self getSongInfoWithSong:firstSong];
                _currentPlayIndex = 0;
            }
        }
        
    }
    
    sender.selected = !sender.selected;
    [self.tableView reloadData];
}


/// 上一曲
- (IBAction)lastSong:(UIButton *)sender {
    
    if (!self.searchData.count) {
        return;
    }
    _playTime = 0;
    /// 暂停封面图册自转动画
    [self pauseLayer:self.albumImgView.layer];
    [_player pause];
    
    if (_hadRefreshData == YES) {  // 如果数据列表刷新了
        
        XMSearchMusicModel *firstSong = self.searchData.firstObject;
        [self getSongInfoWithSong:firstSong];
        _currentPlayIndex = 0;
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        [self.tableView reloadData];
        _hadRefreshData = NO;
        return;
    }
    
    if (_currentPlayIndex == 0) {  // 列表的第一首
        
        if (self.playMode == PlayLoopModeFree) { // 随机播放
            
            int nextIndex = (int) arc4random() % _searchData.count;
            if (nextIndex == _currentPlayIndex) {
                self.searchData.count == 1 ? (_currentPlayIndex = 0) : (_currentPlayIndex = nextIndex+1);
                (_currentPlayIndex > _searchData.count -1) ? (_currentPlayIndex = 0) : _currentPlayIndex;
            }else {
                _currentPlayIndex = nextIndex;
            }
            XMSearchMusicModel *nextSong = self.searchData[_currentPlayIndex];
            [self getSongInfoWithSong:nextSong];
            
        }else { // 非随机播放
            
            _currentPlayIndex = self.searchData.count - 1;
            XMSearchMusicModel *lastSong = self.searchData.lastObject;
            [self getSongInfoWithSong:lastSong];
            // 滚动底部
            if (self.tableView.contentSize.height > self.tableView.frame.size.height)
            {
                CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
                [self.tableView setContentOffset:offset animated:NO];
            }
        }
        
    }else {  // 播放上一首
        
        
        if (self.playMode == PlayLoopModeFree) { // 随机播放
            int nextIndex = (int) arc4random() % _searchData.count;
            if (nextIndex == _currentPlayIndex) {
                self.searchData.count == 1 ? (_currentPlayIndex = 0) : (_currentPlayIndex = nextIndex+1);
                (_currentPlayIndex > _searchData.count -1) ? (_currentPlayIndex = 0) : _currentPlayIndex;
            }else {
                _currentPlayIndex = nextIndex;
            }
            
        }else {
            _currentPlayIndex --;
        }
        
        XMSearchMusicModel *nextSong = self.searchData[_currentPlayIndex];
        [self getSongInfoWithSong:nextSong];
    }
    
    self.isPlaying = NO;
    [self.tableView reloadData];
}

/// 下一曲
- (IBAction)nextSong:(UIButton *)sender {
    
    if (!self.searchData.count) {
        return;
    }
    
    _playTime = 0;
    /// 暂停封面图册自转动画
    [self pauseLayer:self.albumImgView.layer];
    [_player pause];
    
    if (_hadRefreshData == YES) {  // 如果数据列表刷新了
        
        XMSearchMusicModel *firstSong = self.searchData.firstObject;
        [self getSongInfoWithSong:firstSong];
        _currentPlayIndex = 0;
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        [self.tableView reloadData];
        _hadRefreshData = NO;
        return;
    }
    
    if (_currentPlayIndex < self.searchData.count -1) {  // 不是列表最后一首
        
//        NSLog(@"不是列表最后一首 %ld ",_currentPlayIndex);
        if (self.playMode == PlayLoopModeFree) { // 随机播放
            
            int nextIndex = (int) arc4random() % _searchData.count;
            if (nextIndex == _currentPlayIndex) {
                self.searchData.count == 2 ? (_currentPlayIndex = 1) : (_currentPlayIndex = nextIndex+1);
                (_currentPlayIndex > _searchData.count -1) ? (_currentPlayIndex = 0) : _currentPlayIndex;
//                NSLog(@"随机播放==相同歌曲情况%ld",_currentPlayIndex);
            }else {
                _currentPlayIndex = nextIndex;
            }
            
        }else {
            _currentPlayIndex ++;
        }
        
        XMSearchMusicModel *nextSong = self.searchData[_currentPlayIndex];
        [self getSongInfoWithSong:nextSong];
        
    }else {  // 列表最后一首
        
        if (self.playMode == PlayLoopModeFree) { // 随机播放
            
//            NSLog(@"列表最后一首 %ld ",_currentPlayIndex);
            int nextIndex = (int) arc4random() % _searchData.count;
            if (nextIndex == _currentPlayIndex) {
                self.searchData.count == 2 ? (_currentPlayIndex = 0) : (_currentPlayIndex = nextIndex+1);
                (_currentPlayIndex > _searchData.count -1) ? (_currentPlayIndex = 0) : _currentPlayIndex;
//                NSLog(@"第一首 随机播放==相同歌曲情况%ld",_currentPlayIndex);
            }else {
                _currentPlayIndex = nextIndex;
            }
            XMSearchMusicModel *nextSong = self.searchData[_currentPlayIndex];
            [self getSongInfoWithSong:nextSong];
            
        }else { // 从第一首开始
            
            XMSearchMusicModel *firstSong = self.searchData.firstObject;
            [self getSongInfoWithSong:firstSong];
            _currentPlayIndex = 0;
            [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        }
        
    }
    
//    NSString *idxStr = [NSString stringWithFormat:@"当前播放===%ld",_currentPlayIndex];
//    [MBProgressHUD showSingleMessage:idxStr];
//    NSLog(@"%@",idxStr);
    
    self.isPlaying = NO;
    [self.tableView reloadData];
}


/// 添加歌曲首收藏列表
- (IBAction)likeAddToListClick:(id)sender {
//    [MBProgressHUD showSingleMessage:@"收藏歌曲到歌单（未实现）"];
    
    if (_currentPlaySong) {
        
        XMSearchMusicModel *song = _currentPlaySong;
        
        // 查询是否已存在
        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(song.ID)];
        NSArray* array = [XMSearchMusicModel bg_find:DEFAULT_TABLE_NAME where:where];
        if (array.count) {
            [MBProgressHUD showSingleMessage:@"歌曲已存在"];
            return;
        }
        // 保存到歌单
        song.bg_tableName = DEFAULT_TABLE_NAME;
        [song bg_saveOrUpdate];
        
        [MBProgressHUD showSuccess:@"已收藏到我的歌单~"];
        
    }else {
        [MBProgressHUD showSingleMessage:@"请选择要收藏的歌曲"];
    }
}

/// 循环模式
- (IBAction)loopBtnClick:(UIButton *)sender {
    // 选中未单曲循环
//    sender.selected = !sender.selected;
//    if (sender.selected) {
//        [MBProgressHUD showSingleMessage:@"单曲循环"];
//    }else {
//        [MBProgressHUD showSingleMessage:@"列表循环"];
//    }
    self.playMode ++;
    if (self.playMode > 3) {
        self.playMode = PlayLoopModeSingle;
    }
    
    if (self.playMode == PlayLoopModeSingle) { // 单曲循环
        [MBProgressHUD showSingleMessage:@"单曲循环"];
        [self.loopModeBtn setImage:[UIImage imageNamed:@"单曲循环"] forState:UIControlStateNormal];
    }else if(self.playMode == PlayLoopModeAll){ // 列表循环
        [MBProgressHUD showSingleMessage:@"列表循环"];
        [self.loopModeBtn setImage:[UIImage imageNamed:@"列表循环"] forState:UIControlStateNormal];
    }else if (self.playMode == PlayLoopModeFree){ // 随机播放
        [MBProgressHUD showSingleMessage:@"随机播放"];
        [self.loopModeBtn setImage:[UIImage imageNamed:@"随机播放"] forState:UIControlStateNormal];
    }
    
    UserDefaults *ud = [UserDefaultsTool userDefaults]?:[[UserDefaults alloc]init];
    ud.playLoopMode = [NSNumber numberWithInteger:self.playMode];
    [UserDefaultsTool saveUserDefaults:ud];
}

/// 全屏、取消全屏播放
- (IBAction)fullScreenBtnClick:(UIButton *)sender {
    
    if (!sender) {
        sender = _fullScreenBtn;
    }
    
    if (sender.selected) {  // 点击时是全屏播放
        
        [self.view sendSubviewToBack:_bgImgView];
        
        _albumImgView.alpha = 0.5;
        self.bgToolBar.alpha = 0.5;
        [UIView animateWithDuration:0.5 animations:^{
            
            self.bgToolBar.alpha = 0;
            _playAreaBgView.backgroundColor = [UIColor whiteColor];
            _playTimeL.textColor = [UIColor blackColor];
            _totalTimeL.textColor = [UIColor blackColor];
        } completion:^(BOOL finished) {
        }];
        
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        self.isShowBgToolBar = NO;
        
    }else {  // 点击时是列表播放
        
        self.bgToolBar.alpha = 0;
//        NSNumber *imageNum = [UserDefaultsTool userDefaults].bgImageAlpha?:@0;
//        _bgImgView.alpha = [imageNum integerValue]/100.0;
        _albumImgView.alpha = 1;
        _playAreaBgView.backgroundColor = [UIColor colorWithWhite:1 alpha:0];
        
        [self.view bringSubviewToFront:_bgImgView];
        [self.view bringSubviewToFront:self.bgToolBar];
        [self.view bringSubviewToFront:_playAreaBgView];
        [self.bgToolBar bringSubviewToFront:_albumImgView];
        
        [UIView animateWithDuration:0.5 animations:^{
        
            self.bgToolBar.alpha = 1;
            _albumImgView.alpha = 1;
//            _bgImgView.alpha = 1;
            _playTimeL.textColor = [UIColor whiteColor];
            _totalTimeL.textColor = [UIColor whiteColor];
        } completion:^(BOOL finished) {
            [self.view bringSubviewToFront:self.bgToolBar];
            [self.view bringSubviewToFront:_playAreaBgView];
        }];
        
        // 设置封面图册
        XMSearchMusicModel *song = self.currentPlaySong;
        if (!self.currentPlaySong && self.searchData.count>0) {
            song = self.searchData[_currentPlayIndex];
        }
        NSString *imgStr = song.album[@"cover"];
        [_albumImgView sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"winterCute.png"]];
        _fullScreenSongNameL.text = song.name;
        NSDictionary *artists = song.artists.firstObject;
        NSString *singerName = artists[@"name"];
        _fullScreenSingerNameL.text = singerName;
        
        if (self.isPlaying && self.playBtn.selected) {
            
//            NSLog(@"点击全屏时正在播放");
            if ((_rotationAnimation.duration < 10)) {
                // 开始封面自转动画
                [self makeImgViewCircleAnimationWithState:YES];
            }
        }else {
            [self pauseLayer:self.albumImgView.layer];
        }
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        self.isShowBgToolBar = YES;
    }
    
    [self setNeedsStatusBarAppearanceUpdate];
    sender.selected = !sender.selected;
}

/// 监听系统声音
- (void)volumeChanged:(NSNotification *)notification
{
    CGFloat volume = [notification.userInfo[@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
    
//    NSString *voice = [NSString stringWithFormat:@"%f",volume];
//    [MBProgressHUD showSingleMessage:voice];
    
    _showVolueSlider.value = volume;
}

/// 初始化音量控制
-(void)setupControlVolume
{
    NSLog(@"初始化音量===%f",[[AVAudioSession sharedInstance] outputVolume]);
   _showVolueSlider.value = [[AVAudioSession sharedInstance] outputVolume];
}

/// 改变音量
- (void)changeVolume:(UISlider *)slider
{
    if (!_volumeView) {
        
        // 隐藏系统的声音改变默认提示View
        _volumeView = [[MPVolumeView alloc]initWithFrame:CGRectMake(-1000, -1000, 100, 100)];
        
        _volumeView.showsRouteButton = NO;
        //默认YES，这里为了突出，故意设置一遍
        _volumeView.showsVolumeSlider = YES;
        
        [_volumeView sizeToFit];
        //    [_volumeView setFrame:CGRectMake(1000, 1000, 100, 100)];
        
        [self.bgToolBar addSubview:_volumeView];
        [_volumeView userActivity];
        
        for (UIView *view in [_volumeView subviews]){
            if ([[view.class description] isEqualToString:@"MPVolumeSlider"]){
                _volumeSlider = (UISlider*)view;
                break;
            }
        }
        //设置默认打开视频时声音为0.3，如果不设置的话，获取的当前声音始终是0。现在是设置当前系统音量
        [_volumeSlider setValue:[[AVAudioSession sharedInstance] outputVolume]];
        
        //获取最是刚打开时的音量值
        //    _volumeValue = _volumeSlider.value;
        
        //设置展示音量条的值
        _showVolueSlider.value = _volumeSlider.value;
    }
    
    _volumeSlider.value = _showVolueSlider.value;
}


/// 让图片不断自转 (state == 1 创建新的)
- (void)makeImgViewCircleAnimationWithState:(int)state
{
    if (!_albumImgView) {
        return;
    }
    
    if (state == 1) {  // 创建新的动画
        
        NSLog(@"===== 创建新的动画");
        CABasicAnimation* rotationAnimation;
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
        rotationAnimation.duration = 20;
        rotationAnimation.cumulative = YES;
        rotationAnimation.repeatCount = 999999;
        rotationAnimation.removedOnCompletion = NO;
        [self.albumImgView.layer addAnimation:rotationAnimation forKey:albumImageViewAnimationKey];
        _rotationAnimation = rotationAnimation;
    }
    
    [self resumeLayer:self.albumImgView.layer];
}

/// 移除封面图册自转动画
- (void)removeImgViewCircleAnimation
{
    [self.albumImgView.layer removeAnimationForKey:albumImageViewAnimationKey];
}

// 暂停layer上面的动画
- (void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

// 继续layer上面的动画
- (void)resumeLayer:(CALayer*)layer
{
    if (!layer) {
        [self makeImgViewCircleAnimationWithState:1];
    }
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}


/// 点击我的歌单
- (IBAction)mySongListBtnClick:(id)sender {
//    [MBProgressHUD showSingleMessage:@"我的歌单（未实现）"];
    
    AlbumListController *albumVc = [[AlbumListController alloc]init];
    UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:albumVc];
    [self presentViewController:navVC animated:YES completion:nil];
}

/// 点击设置
- (IBAction)settingBtnClick:(id)sender {
//    [MBProgressHUD showSingleMessage:@"设置（未实现）"];
    
    SettingViewController *settingVc = [[SettingViewController alloc]init];
    UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:settingVc];
    [self presentViewController:navVC animated:YES completion:nil];
}


#pragma mark - other 其他一些处理

/// 状态栏
- (UIStatusBarStyle)preferredStatusBarStyle {
    
    if (self.isShowBgToolBar) {
        
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    
    return UIStatusBarAnimationFade;
}

- (UIToolbar *)bgToolBar
{
    if (!_bgToolBar) {
        
        NSLog(@"!!!! 创建 _bgToolBar ！！！");
        
        _bgToolBar= [[UIToolbar alloc]initWithFrame:self.view.window.bounds];
        _bgToolBar.barStyle = UIBarStyleBlack;
        //            bgToolbar.alpha = 0.7;
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBgToolBar)];
//        [tap setNumberOfTapsRequired:1];
//        [_bgToolBar addGestureRecognizer:tap];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        
        // 歌曲名
        UILabel *songNameL = [[UILabel alloc]initWithFrame:CGRectMake(0, 40, screenSize.width, 20)];
        songNameL.textColor = [UIColor whiteColor];
        songNameL.textAlignment = NSTextAlignmentCenter;
        [_bgToolBar addSubview:songNameL];
        _fullScreenSongNameL = songNameL;
        // 歌手
        UILabel *singerNameL = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, screenSize.width, 20)];
        singerNameL.textColor = [UIColor whiteColor];
        singerNameL.textAlignment = NSTextAlignmentCenter;
        singerNameL.font = [UIFont systemFontOfSize:12];
        [_bgToolBar addSubview:singerNameL];
        _fullScreenSingerNameL= singerNameL;
        
        // 音量图标
        UIImageView *volceView = [[UIImageView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(singerNameL.frame)+20, 20, 20)];
        volceView.image = [UIImage imageNamed:@"音量"];
        [_bgToolBar addSubview:volceView];
        
        /// 音量调节
        UISlider *showVolueSlider = [[UISlider alloc]initWithFrame:CGRectMake(50, CGRectGetMaxY(singerNameL.frame)+10, screenSize.width - 70, 40)];
        showVolueSlider.minimumTrackTintColor = [UIColor orangeColor];
        [showVolueSlider addTarget:self action:@selector(changeVolume:) forControlEvents:UIControlEventValueChanged];
        [_bgToolBar addSubview:showVolueSlider];
        _showVolueSlider = showVolueSlider;
        
        // 初始化音量
        [self setupControlVolume];
        [self changeVolume:_showVolueSlider];
        
        CGFloat WH = screenSize.width *0.5;
        // 封面图片背景
        UIImageView *albumBg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WH+(WH*0.4), WH+(WH*0.4))];
        albumBg.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
        albumBg.layer.cornerRadius = albumBg.frame.size.width *0.5;
        albumBg.clipsToBounds = YES;
        [_bgToolBar addSubview:albumBg];
        albumBg.center = self.bgToolBar.center;
        
        // 封面图片
        UIImageView *albumImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WH, WH)];
        [_bgToolBar addSubview:albumImgView];
        albumImgView.center = self.bgToolBar.center;
        albumImgView.layer.cornerRadius = WH *0.5;
        albumImgView.clipsToBounds = YES;
        albumImgView.layer.borderColor = [UIColor blackColor].CGColor;
        albumImgView.layer.borderWidth = 5;
        _albumImgView = albumImgView;
        
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBgImageView)];
//        [tap setNumberOfTapsRequired:1];
//        [_albumImgView addGestureRecognizer:tap];
        
//        [_bgToolBar sendSubviewToBack:albumBg];
        [self.view addSubview:_bgToolBar];
    }
    return _bgToolBar;
}

//- (void)tapBgImageView
//{
//    if (self.playBtn.selected) {
//        [self makeImgViewCircleAnimationWithState:1];
//    }
//}

// 重写父类方法，接受外部事件的处理(控制中心)
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) { // 得到事件类型
                
            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                [self lastSong:self.lastSongBtn];
                break;
                
            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                [self nextSong:self.nextSongBtn];
                break;
                
            case UIEventSubtypeRemoteControlPlay: //播放
                [self playBtnClick:_playBtn];
                break;
                
            case UIEventSubtypeRemoteControlPause: // 暂停 ios7
                [self playBtnClick:_playBtn];
                break;
                
            default:
                break;
        }
    }
}

/// 设置锁屏状态播放信息
- (void)setupNotificationSong:(XMSearchMusicModel *)song
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    //设置歌曲题目
    NSString *name = song.name;
    [dict setObject:name forKey:MPMediaItemPropertyTitle];
    
    //设置歌手名
    NSDictionary *artists = song.artists.firstObject;
    NSString *singerName = artists[@"name"];
    [dict setObject:singerName forKey:MPMediaItemPropertyArtist];
    
    //设置专辑名
    NSString *albumName = song.album[@"name"];
    [dict setObject:albumName forKey:MPMediaItemPropertyAlbumTitle];
    
    //设置显示的图片
    NSString *imgStr = song.album[@"cover"];
    UIImageView *tempImgView = [[UIImageView alloc]init];
    [tempImgView sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"winterCute.png"]];
    
    UIImage *newImage = tempImgView.image;
    [dict setObject:[[MPMediaItemArtwork alloc] initWithImage:newImage]
             forKey:MPMediaItemPropertyArtwork];
    
    //设置歌曲时长
    double totalTime = self.sumPlayOperation>0.0?self.sumPlayOperation:0.0;
    [dict setObject:[NSNumber numberWithDouble:totalTime] forKey:MPMediaItemPropertyPlaybackDuration];
    
    //设置已经播放时长
    double playTime = _playTime>0.0?_playTime:0.0;
    [dict setObject:[NSNumber numberWithDouble:playTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    //更新字典
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

/// 监控当前网络
- (void)checkNetworkState
{
    _networkL.textColor = [UIColor blueColor];
    [SFKHTTPTool monitorNetworkStatusChange:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
            {
                NSLog(@"AFNetworkReachabilityStatusNotReachable");
                _networkL.text = @"当前无网络连接";
                _networkL.textColor = [UIColor redColor];
                [MBProgressHUD showSingleMessage:@"当前无网络连接"];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                _networkL.text = @"当前WiFi网络";
                _networkL.textColor = [UIColor blueColor];
                NSLog(@"AFNetworkReachabilityStatusReachableViaWiFi");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                _networkL.text = @"当前蜂窝移动网络!!";
                _networkL.textColor = [UIColor purpleColor];
                [MBProgressHUD showSingleMessage:@"当前使用蜂窝移动网络"];
                NSLog(@"AFNetworkReachabilityStatusReachableViaWWAN");
            }
                break;
            case AFNetworkReachabilityStatusUnknown:
            {
                _networkL.text = @"当前未知网络";
                _networkL.textColor = [UIColor redColor];
                [MBProgressHUD showSingleMessage:@"当前未知网络"];
                NSLog(@"AFNetworkReachabilityStatusUnknown");
            }
                break;
                
            default:
                break;
        }
    }];
}

#pragma mark - textview delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"textFieldShouldReturn");
    if (textField.text.length>0) { // 发送
        NSLog(@"self.searchF.text==%@",self.searchF.text);
        [self searchMusic:nil];
    }
    [self.view endEditing:YES];
    return YES;
    
}

#pragma mark - 加载本地背景图片（如果有）
- (void)setBgImageViewImage
{
    //    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:BG_IMAGE_NAME];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    
    if (!blHave) {
        NSLog(@"no have 本地没有背景图");
        return ;
    }else {
        NSLog(@" have 本地有背景图,设置它");
        UIImage *bgImage = [[UIImage alloc]initWithContentsOfFile:uniquePath];
        _bgImgView.image = bgImage;
    }
}

#pragma mark - 设置背景图片
- (void)setBgImage:(NSNotification *)noti
{
    UIImage *bgImage = noti.object;
    
//    NSLog(@"bgImage==%@",bgImage);
    
    _bgImgView.image = bgImage;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD showSuccess:@"已经 OK~"];
    });
}

#pragma mark - 设置背景图片透明度
- (void)setBgImageAlpha:(NSNotification *)noti
{
    NSNumber *alphaNum = noti.object;
    
    NSLog(@"alphaNum==%@",alphaNum);
    
    if ([alphaNum integerValue] <= 100) {
        
        _bgImgView.alpha = [alphaNum integerValue]/100.0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showSuccess:@"已经 OK~"];
        });
        
        // 保存到本地
        UserDefaults *ud = [UserDefaultsTool userDefaults]?:[[UserDefaults alloc]init];
        ud.bgImageAlpha = alphaNum;
        [UserDefaultsTool saveUserDefaults:ud];
        
    }else {
        
        _bgImgView.alpha = 1.0;
        [MBProgressHUD showError:@"输入透明度有误"];
        
        // 保存到本地
        UserDefaults *ud = [UserDefaultsTool userDefaults]?:[[UserDefaults alloc]init];
        ud.bgImageAlpha = @100;
        [UserDefaultsTool saveUserDefaults:ud];
    }
}

#pragma mark - 设置播放列表背景透明度
- (void)setTableViewBgAlpha:(NSNotification *)noti
{
    NSNumber *alphaNum = noti.object;
    
    NSLog(@"alphaNum==%@",alphaNum);
    
    if ([alphaNum integerValue] <= 100) {
        
        self.tableView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:[alphaNum integerValue]/100.0];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showSuccess:@"已经 OK~"];
        });
        
        // 保存到本地
        UserDefaults *ud = [UserDefaultsTool userDefaults]?:[[UserDefaults alloc]init];
        ud.playListBgAlpha = alphaNum;
        [UserDefaultsTool saveUserDefaults:ud];
        
    }else {
        
        self.tableView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
        [MBProgressHUD showError:@"输入透明度有误"];
        
        // 保存到本地
        UserDefaults *ud = [UserDefaultsTool userDefaults]?:[[UserDefaults alloc]init];
        ud.playListBgAlpha = @100;
        [UserDefaultsTool saveUserDefaults:ud];
    }
}

#pragma mark - 设置播放列表的数据为 我的收藏中的数据
- (void)playMyAlbumSongs:(NSNotification *)noti
{
    NSMutableArray *songs = noti.object;
    NSString *indexStr  = noti.userInfo[@"indexRow"];
    
    NSLog(@"songs==%@",songs);
    if (songs.count) {
        self.searchData = songs;
        _currentPlayIndex = [indexStr integerValue];
        _currentPlaySong = self.searchData[_currentPlayIndex];
        [self getSongInfoWithSong:_currentPlaySong];
        NSLog(@"播放==%@",_currentPlaySong.name);
        
        [self.tableView reloadData];
    }
}

#pragma mark - 2017-12-25 新增从列表直接收藏歌曲
//以下是添加收藏功能的代码
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewRowAction *layTopRowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"收藏" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
        XMSearchMusicModel *song = self.searchData[indexPath.row];
        
        // 查询是否已存在
        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(song.ID)];
        NSArray* array = [XMSearchMusicModel bg_find:DEFAULT_TABLE_NAME where:where];
        if (array.count) {
            [MBProgressHUD showSingleMessage:@"歌曲已存在"];
            return;
        }
        // 保存到歌单
        song.bg_tableName = DEFAULT_TABLE_NAME;
        [song bg_saveOrUpdate];
        
        [MBProgressHUD showSuccess:@"已收藏到我的歌单~"];
        
    }];
    layTopRowAction1.backgroundColor = [UIColor orangeColor];
    
    NSArray *arr = @[layTopRowAction1];
    return arr;
    
}


@end
